const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const user = require('./routes/user')
const menu = require('./routes/menu')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


async function checkUserPermission(ctx) {

    //如果是白名单,则直接过
    const whiteJson = require('./auth/white.json')

    var is_white = false;
    if (whiteJson.hasOwnProperty(ctx.path)) {
        is_white = true
    }

    console.log(ctx, "============ctx===========");

    var token = ctx.request.query['token'] || ctx.request.body['token'] || ctx.header['token'] || '';

    if (token.length == 0 && !is_white) {
        return false;
    }

    //如果有token就把用户信息带上
    const redisMap = require('./auth/redis.json')

    if (redisMap.hasOwnProperty(token)) {
        ctx.request.body.token_user = redisMap[token];
        return true;
    } else {
        if (is_white) {
            return true;
        }
        return false
    }
}


// app.use(async (ctx, next) => {
//     if (await checkUserPermission(ctx)) {
//         await next();
//     } else {
//         ctx.body = {
//             success: false,
//             code: 4001,
//             message: 'token缺失或过期'
//         };
//     }
// });

// routes
app.use(index.routes(), index.allowedMethods())
app.use(user.routes(), user.allowedMethods())
app.use(menu.routes(), menu.allowedMethods())



// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
